package com.example.lib_visitor

import androidx.lifecycle.viewModelScope
import com.example.lib_common.mvi.BaseViewModel
import com.example.lib_common.mvi.ResponseEntity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch

class VisitorViewModel : BaseViewModel<VisitorRepository,VisitorState>() {
    override fun createRepo(): VisitorRepository {
        return VisitorRepository()
    }

    override fun createState(): VisitorState {
        return VisitorState(ResponseEntity(0,"",VisitorEntity()))
    }

    fun addVisitor(map: HashMap<String,Any>){
        mutableContainer.updateRequestState {
            copy(request=true)
        }
        viewModelScope.launch(Dispatchers.IO){
            repo.requestAllSpace(map).flowOn(Dispatchers.IO)
                .collect {
                    mutableContainer.updateRequestState {
                        copy(request=false,complete=true)
                    }
                    mutableContainer.updateUiState {
                        copy(entity=it)
                    }
                }
        }
    }
}